package groups

import (
	es7 "GinTemplate/internal/databases/es"
	"GinTemplate/internal/models"
	"context"
	"encoding/json"
	"fmt"
	"github.com/mitchellh/mapstructure"
	"io"
	"strings"
)

var (
	es = es7.ES
)

func Search(from int, size int) (c []models.Group, total float64, err error) {
	query := fmt.Sprintf(`{
		"query": {
			"match_all": {}
		},
		"from": %d,
		"size": %d
	}`, from, size)

	indexName := "telegram_information"
	resp, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex(indexName),
		es.Search.WithBody(strings.NewReader(query)),
	)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return
	}

	var result map[string]interface{}
	err = json.Unmarshal(body, &result)
	if err != nil {
		return
	}
	// 提取命中的文档信息
	if hits, ok := result["hits"].(map[string]interface{}); ok {
		// total
		total = hits["total"].(map[string]interface{})["value"].(float64)
		if hitsList, ok := hits["hits"].([]interface{}); ok {
			for _, hit := range hitsList {
				if hit, ok := hit.(map[string]interface{}); ok {
					id := hit["_id"].(string)
					if source, ok := hit["_source"].(map[string]interface{}); ok {
						// 处理每个文档的信息
						var group models.Group
						mapstructure.Decode(source, &group)
						group.ID = id
						c = append(c, group)
					}
				}
			}
		}
	}
	return
}

func Create(group models.Group) (err error) {
	body, err := json.Marshal(group)
	if err != nil {
		return err
	}
	_, err = es.Index(
		"telegram_information",
		strings.NewReader(string(body)),
		es.Index.WithContext(context.Background()),
	)
	return
}

func Update(id string, updateGroup models.UpdateGroup) (err error) {
	body, err := json.Marshal(updateGroup)
	if err != nil {
		return err
	}

	_, err = es.Update(
		"telegram_information",
		id,
		strings.NewReader(string(body)),
	)
	return
}

func Delete(id string) (err error) {
	_, err = es.Delete(
		"telegram_information",
		id,
		es.Delete.WithContext(context.Background()),
	)
	return
}
